package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

// 枚举转换器工厂
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    //制造转换器的方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体转换器
        return new Converter<String,T>() {
            //定义转换方法
            @Override
            public T convert(String source) {
                //1.遍历枚举
                for (T enumConstant : targetType.getEnumConstants()) {
                    //2.判断code是否相等
                    if (enumConstant.getCode()== Integer.parseInt(source)) {
                        //3.如果相等，则返回
                        return enumConstant;
                    }
                }
                throw new RuntimeException("非法类型异常");
            }
        };
    }
}
